from .base_scraper import BaseScraper
import re
import logging

class JDScraper(BaseScraper):
    def __init__(self):
        super().__init__()
        self.base_url = "https://search.jd.com/Search"
        self.logger = logging.getLogger(__name__)
    
    def search(self, keyword):
        """搜索京东商品"""
        try:
            params = {
                'keyword': keyword,
                'enc': 'utf-8',
                'pvid': '1'
            }
            
            soup = self.get(self.base_url, params)
            if not soup:
                return []
            
            products = []
            items = soup.find_all('li', {'data-sku': True})
            
            for item in items[:10]:  # 限制前10个结果
                try:
                    # 商品标题
                    title_elem = item.find('div', class_='p-name')
                    if not title_elem:
                        continue
                    
                    title = title_elem.get_text().strip()
                    
                    # 价格
                    price_elem = item.find('div', class_='p-price')
                    if price_elem:
                        price_str = price_elem.get_text().strip()
                        price_match = re.search(r'(\d+\.?\d*)', price_str)
                        price = float(price_match.group(1)) if price_match else 0
                    else:
                        continue
                    
                    # 图片
                    img_elem = item.find('img')
                    img_url = img_elem.get('data-lazy-img') or img_elem.get('src', '')
                    if img_url.startswith('//'):
                        img_url = 'https:' + img_url
                    
                    # 销量
                    comment_elem = item.find('div', class_='p-commit')
                    sales = '0'
                    if comment_elem:
                        sales_text = comment_elem.get_text().strip()
                        sales_match = re.search(r'(\d+)', sales_text)
                        sales = sales_match.group(1) if sales_match else '0'
                    
                    products.append({
                        'title': title,
                        'price': price,
                        'image': img_url,
                        'sales': f"{sales}+",
                        'url': f"https://item.jd.com/{item.get('data-sku')}.html",
                        'platform': 'jd',
                        'isBestSeller': len(products) == 0  # 第一个作为销量冠军
                    })
                    
                except Exception as e:
                    self.logger.error(f"解析京东商品失败: {str(e)}")
                    continue
            
            return products
            
        except Exception as e:
            self.logger.error(f"京东搜索失败: {str(e)}")
            return []
